<?php
require_once('sub.inc.php');

if(!is_null($_POST['mode'])){
	$mode = $_POST['mode'];
}else{
	if(!is_null($_GET['mode'])){
		$mode = $_GET['mode'];
	}else{
		die("No mode");
	}
}

recRequest();

if($mode == "latest" || $mode == "latestfull"){
	$res = mysqli_query($GLOBALS['con'], "SELECT * FROM `enwn_articles` WHERE `deleted`=FALSE and `expired`=FALSE ORDER BY `id` DESC LIMIT 0,20");
	$a = 0; $ray = array();
	while($row = mysqli_fetch_array($res)){
		$a++;
		if($mode == "latestfull"){
			//$ray[$a] = array("id"=>$row['id'],"title"=>utf8_encode($row['title']),"url"=>$row['url'],"revid"=>$row['revid'],"last_update"=>$row['last_update'],"fulltext"=>utf8_encode($row['fulltext']));
			$ray[$a] = array("id"=>$row['id'],"title"=>$row['title'],"url"=>$row['url'],"revid"=>$row['revid'],"last_update"=>$row['last_update'],"fulltext"=>$row['fulltext']);
		}else{
			//$ray[$a] = array("id"=>$row['id'],"title"=>utf8_encode($row['title']),"url"=>$row['url'],"revid"=>$row['revid'],"last_update"=>$row['last_update']);
			$ray[$a] = array("id"=>$row['id'],"title"=>$row['title'],"url"=>$row['url'],"revid"=>$row['revid'],"last_update"=>$row['last_update']);
		}
	}
	print(json_encode($ray));

}elseif($mode == "submitbug"){
	$email = $_POST['email'];
	$summary = $_POST['summary'];
	$desc = $_POST['desc'];
	if(is_null($email) || is_null($summary) || is_null($desc)){
		die("ERROR-REQUIRED");
	}

	$res = mysqli_query($GLOBALS['con'], "INSERT INTO `enwn_bugs` (`email`,`summary`,`desc`) VALUES ('$email', '$summary', '$desc')");
	print "Done";

}elseif($mode == "textonly"){
	if(is_null($_POST['id'])){
		die("ERROR-REQUIRED");
	}
	$res = mysqli_query($GLOBALS['con'], "SELECT `fulltext`,`deleted`,`expired` FROM `enwn_articles` WHERE `id`='".$_POST['id']."'");
	if($row = mysqli_fetch_array($res)){
		if($row['deleted'] == true){
			print "ERROR-PAGEDELETED";
		}elseif($row['expired'] == true){
			print "ERROR-PAGEEXPIRED";
		}else{
			print $row['fulltext'];
		}
	}else{
		print "ERROR-TEXTONLY";
	}
}elseif($mode == "test"){
	
}else{
	print "ERROR\n";
	print_r($_POST);
}


function recRequest(){

	$ua = $_SERVER['HTTP_USER_AGENT'];
	$ip = $_SERVER['REMOTE_ADDR'];
	if($_SERVER['REQUEST_METHOD'] == "GET"){
		$get = json_encode($_GET);
	}else{
		$post = json_encode($_POST);
	}

	$res = mysqli_query($GLOBALS['con'], "INSERT INTO `enwn_requests` (`get`,`post`,`useragent`,`ip`) VALUES ('$get','$post','$ua','$ip')");
	//print mysqli_error($GLOBALS['con']);

}
